let db = require("../db/index");
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要加1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
}
// 查询所有角色
exports.allRole = (req, res) => {
    var sql =
        'select * from role';
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send(data);
    });
};
//更新已有数据
exports.editRole = (req, res) => {
    console.log(req.body);
    const currentDate = new Date();
    const now = formatDate(currentDate)
    const { roleName, roleIntro, roleState, selectNode, roleID, addMan } = req.body
    var sql =
        `update role set RoleName='${roleName}',RoleIntro='${roleIntro}',addman='${addMan}',addDate='${now}',Permission='${selectNode}',RoleState='${roleState}' where ID=${roleID}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send({ status: 200 });
    });
};
//停用和启用
exports.updateRoleState = (req, res) => {
    console.log(req.body);
    const { str, id } = req.body
    var sql =
        `update role set RoleState='${str}' where ID=${id}`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send({ status: 200 });
    });
};
// 新增数据
exports.insertRole = (req, res) => {
    const { roleName, roleIntro, roleState, selectNode, addMan } = req.body
    const currentDate = new Date();
    const now = formatDate(currentDate)
    var sql =
        `insert into role(RoleName,RoleIntro,RoleState,addman,addDate,Permission)values('${roleName}','${roleIntro}','${roleState}','${addMan}','${now}','${selectNode}')`;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send({ status: 200 });
    });
};
//查询某个权限
exports.someRole = (req, res) => {
    const {id}=req.body
    var sql =
        'select Permission from role where ID='+id;
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send(data[0]);
    });
};